<template>
  <div class="product">
    <el-form ref="form" :data="form" :label-width="formLabelWidth">
      <el-form-item label="商品背景图">
        <el-upload
          class="avatar-uploader"
          action="/api/file/upload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="form.image_url" :src="form.image_url" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <el-form-item label="商品详情图">
        <el-upload
          action="/api/file/upload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          :file-list="imageList"
          multiple>
          <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>

      <el-form-item label="商品名称">
        <el-input v-model="form.name" placeholder="请输入商品名称" clearable/>
      </el-form-item>

      <el-form-item label="商品价格">
        <el-input v-model="form.price" placeholder="请输入商品价格" clearable/>
      </el-form-item>

      <el-form-item label="商品库存">
        <el-input v-model="form.inventory" placeholder="请输入商品库存" clearable/>
      </el-form-item>

      <el-form-item label="商品种类">
        <el-select v-model="form.category_detail_id">
          <el-option v-for="(category, index) in categoryDetail" :key="index" :label="category.label" :value="category.value"/>
        </el-select>
      </el-form-item>

      <el-form-item label="生产地址">
        <el-input v-model="form.address" placeholder="请输入生产地址" clearable/>
      </el-form-item>

      <el-form-item label="是否设为热门">
        <el-switch v-model="form.hot"/>
      </el-form-item>
      <el-form-item label="商品备注">
        <el-input v-model="form.remark" style="width:300px;" type="textarea" rows="6" placeholder="备注" clearable/>
      </el-form-item>
      <div style="margin: 50px;">
      <tinymce :width="900" :height="300" id='tinymce' v-model="form.content"></tinymce>
      </div>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">保存</el-button>
        <el-button @click="goBack">返回</el-button>
      </el-form-item>
    </el-form>
  </div>

</template>

<script>
import productApi from '@/api/product.js'
import categoryDetailApi from '@/api/categoryDetail'
import Tinymce from '@/components/Tinymce'
const defalultForm = {
  id: '',       // 商品id
  image_url: '',  // 商品背景图
  image_detail_url: '',  // 商品详情图
  name: '',     // 商品名称
  price: null,  // 商品价格
  category: '',     // 商品种类
  address: '',      // 生产地址
  inventory: null,  // 商品库存
  hot: false,           // 是否设为热门
  category_detail_id: null, // 商品类别id
  remark: '',        // 备注
  content: ''
}
export default {
  components: {
    Tinymce
  },
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      formLabelWidth: 100 + 'px',
      form: Object.assign({}, defalultForm),
      categoryDetail: [],
      imageUrl: '',
      imageList: []
    }
  },
  computed: {
    isEdit() {
      return this.$route.meta.isEdit
    },
    id() {
      return this.$route.params.id
    }
  },
  created() {
    if(this.isEdit) {
      this.getProductById()
    }
    this.getCategoryDetails()
  },
  methods: {
    // 获取商品类别明细
    async getCategoryDetails() {
      const query = {
        page: 0,
        limit: 9999
      }
      const result = await categoryDetailApi.getCategoryDetails(query)
      result.data.rows.forEach(value => {
        const obj = {
          label: value.name,
          value: value.id
        }
        this.categoryDetail.push(obj)
      })
    },
    // 添加或修改商品
    async onSubmit() {
      if(this.isEdit) {
        console.log(this.form)
        const result = await productApi.updateProduct(this.id, this.form)
        if(result.code===0) {
          this.$message.success('修改成功')
        }else {
          this.$message.warning('修改失败')
        }
      }else {
        console.log(this.form)
        const result = await productApi.addProduct(this.form)
        if(result.code===0) {
          this.$message.success('添加成功')
        }else {
          this.$message.warning('添加失败')
        }
      }
      this.goBack()
      this.reload()
    },
    // 根据id获取商品
    async getProductById() {
      let vm = this
      const result = await productApi.getProductById(this.id)
      this.form = result.data
      if(result.data.image_detail_url) {
        const list = result.data.image_detail_url.split(',')
        list.forEach(item => {
          var obj = {} 
          let index = item.lastIndexOf('\/')
          let fileName  = item.substring(index + 1, item.length) //最后的文件名截取出来
          vm.$set(obj,'name',fileName)
          vm.$set(obj,'url',item)  //修改files里面的结构（name,url）
          vm.imageList.push(obj)
        })
      }
      if(result.data.hot===0) {
        this.form.hot = false
      }else {
        this.form.hot = true
      }
    },
    // 返回
    goBack() {
      this.$router.go(-1)
    },
    handleAvatarSuccess(res, file) {
      console.log(res)
      this.form.image_url = res.filename;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    handleRemove(file, fileList) {
      console.log(fileList)
      const list = []
       fileList.forEach(value => {
         list.push(value.url)
       })
      console.log(list)
      this.form.image_detail_url = list.toString()
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleSuccess(response, file, fileList) {
      console.log(fileList)
      const list = []
      fileList.forEach((value, index) => {
        if(value.response) {
          list.push(value.response.filename)
        }else {
          list.push(value.url)
        }
      })
      console.log(list)
      this.form.image_detail_url = list.toString()
    }
  },
  inject: ['reload']
}
</script>
<style lang="less" scoped>
  .product {
    margin-top: 20px;
    .el-input {
      width: 300px;
    }
    .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
